<template>
  <div class="content_index">
    <div class="ci_header">
      <div class="ci_left sec-title">
        <el-icon
          style="vertical-align: middle; display: unset; cursor: pointer"
          @click="backList()"
          ><Back
        /></el-icon>
        <span>{{ route.name }}</span>
      </div>
    </div>
    <div class="ci_content" style="margin: 12px 16px">
      <el-form
        label-position="right"
        ref="addExistingFormRef"
        label-width="120px"
        :model="addExistingForm"
        :style="{
          width: addExistingForm.evidenceType === '0' ? '100%' : '50%',
        }"
        :rules="rules"
      >
        <el-form-item label="存证名称：" prop="evidenceName">
          <div style="display: flex">
            <el-input
              style="width: 3rem; height: 32px"
              v-model.trim="addExistingForm.evidenceName"
              placeholder="请输入存证名称(50个字符以内)"
            ></el-input>
          </div>
        </el-form-item>
        <el-form-item label="存证类型：" prop="evidenceType">
          <el-select
            style="width: 3rem"
            v-model="addExistingForm.evidenceType"
            clearable
            placeholder="请选择存证类型"
          >
            <el-option label="哈希" value="0" />
            <el-option label="图片" value="1" />
            <el-option label="文档" value="2" />
            <el-option label="音频视频" value="3" />
            <el-option label="混合类型" value="4" />
          </el-select>
        </el-form-item>

        <el-form-item
          v-show="addExistingForm.evidenceType !== '0'"
          label="是否加密："
          prop="useEncrypt"
        >
          <el-radio-group
            v-model="addExistingForm.useEncrypt"
            placeholder="请选择存证类型"
          >
            <el-radio label="0" size="large">不加密</el-radio>
            <el-radio label="1" size="large">加密</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="文件信息："
          prop="fileInfo"
          v-if="addExistingForm.evidenceType === '0'"
        >
          <el-row
            v-for="(item, index) in addExistingForm.fileInfo"
            :key="index + 1"
            style="padding: 0px 0px 30px 0px"
          >
            <el-col :span="7">
              <el-form-item
                label="文件名称"
                :prop="'fileInfo.' + index + '.name'"
                :rules="{
                  max: 50,
                  required: true,
                  message: '请输入文件名称，50字符以内',
                  trigger: 'blur',
                }"
              >
                <el-input
                  type="text"
                  style="width: 200px"
                  v-model.trim="item.name"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item
                label="文件路径"
                :prop="'fileInfo.' + index + '.url'"
                :rules="{
                  max: 100,
                  required: true,
                  message: '请输入文件路径，100字符以内',
                  trigger: 'blur',
                }"
              >
                <el-input
                  type="text"
                  style="width: 200px"
                  v-model.trim="item.url"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="文件哈希"
                :prop="'fileInfo.' + index + '.hash'"
                :rules="{
                  max: 64,
                  required: true,
                  message: '请输入文件哈希，64字符以内',
                  trigger: 'blur',
                }"
              >
                <el-input
                  type="text"
                  style="width: 200px"
                  v-model.trim="item.hash"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="1" v-if="index !== 0">
              <el-icon class="delete_icon" @click="removeDomain(index)"
                ><Remove
              /></el-icon>
            </el-col>
            <el-col :span="1">
              <el-icon class="add_icon" @click="addDomain"
                ><CirclePlus
              /></el-icon>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item
          label="上传文件："
          v-show="
            addExistingForm.evidenceType === '1' ||
            addExistingForm.evidenceType === '2' ||
            addExistingForm.evidenceType === '3' ||
            addExistingForm.evidenceType === '4'
          "
          prop="file"
        >
          <el-upload
            drag
            :limit="10"
            :on-exceed="handleExceed"
            multiple
            ref="uploadFileCardFront"
            action="#"
            :list-type="
              addExistingForm.evidenceType === '1' && isZip
                ? 'picture-card'
                : addExistingForm.evidenceType === '2'
                ? 'text'
                : 'text'
            "
            :auto-upload="false"
            :on-change="changeAvatarUploadFront"
            :on-preview="handlePictureCardPreview"
            v-model="addExistingForm.file"
          >
            <div class="el-upload__text">拖拽或点击上传文件</div>
            <template #tip>
              <div
                class="el-upload__tip"
                v-show="addExistingForm.evidenceType === '1'"
              >
                限制上传.png，.jpg，.zip格式
              </div>
              <div
                class="el-upload__tip"
                v-show="addExistingForm.evidenceType === '2'"
              >
                限制上传.doc，.docx，.pdf，.ppt，.html，.txt，.xlsx，.zip格式
              </div>
              <div
                class="el-upload__tip"
                v-show="addExistingForm.evidenceType === '3'"
              >
                限制上传mp3，mp4，.zip格式
              </div>
              <div
                class="el-upload__tip"
                v-show="addExistingForm.evidenceType === '4'"
              >
                限制上传.png，.jpg，.doc，.docx，.pdf，.ppt，.html，.txt，.xlsx，mp3，mp4，.zip格式
              </div>
            </template>
          </el-upload>
          <el-dialog v-model="dialogVisible">
            <img
              style="width: 100%"
              w-full
              :src="dialogImageUrl"
              alt="Preview Image"
            />
          </el-dialog>
        </el-form-item>
        <el-form-item>
          <el-button
            :loading="isLoading"
            @click.prevent="inviteMember"
            type="primary"
            >确定</el-button
          >
        </el-form-item>
      </el-form>
      <div
        :style="{
          width: addExistingForm.evidenceType === '0' ? '100%' : '50%',
        }"
        v-if="addExistingForm.evidenceType !== '0'"
        class="txt_content"
      >
        <pre>
1 同一批的存证文件归属于同一次存证，不支持重置；
2 支持文件批量上传，一次不能超过10个文件；
3 不同类型上传文件大小不同，分别如下：图片类：100M，文档类：20M，音视频类：500M，混合类型：200M；
4 您要上传的文件不在系统设定范围内或者是上传文件夹，可将文件打包压缩后上传；
5 文件类型包括：.png，.jpg，.doc，.docx，.pdf，.ppt，.html，.txt，.xlsx，mp3，mp4，.zip
            </pre
        >
      </div>
    </div>
  </div>
</template>
<script setup>
import {
  createEvidenceFile,
  createEvidenceFileHash,
} from "@/api/existingEvidence";
import { useRouter, useRoute } from "vue-router";
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
// 图片放大属性
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const formData = new FormData();
// 点击放大图片
const handlePictureCardPreview = (uploadFile) => {
  if (
    addExistingForm.evidenceType === "1" &&
    (uploadFile.raw.type === "image/jpeg" ||
      uploadFile.raw.type === "image/png")
  ) {
    dialogImageUrl.value = uploadFile.url;
    dialogVisible.value = true;
  }
};
const router = useRouter();
const route = useRoute();
const backList = () => {
  router.go(-1);
};
const isZip = ref(true);
const addExistingFormRef = ref("addExistingForm");
const addExistingForm = reactive({
  evidenceType: "",
  evidenceName: "",
  useEncrypt: "0",
  file: [],
  fileInfo: [
    {
      name: "",
      url: "",
      hash: "",
    },
  ],
});
const isLoading = ref(false);
const rules = reactive({
  evidenceType: [{ required: true, message: "请选择存证类型" }],
  evidenceName: [
    {
      required: true,
      message: "请输入存证名称(50个字符以内)",
    },
    { max: 50, message: "请输入存证名称(50个字符以内)", trigger: "blur" },
  ],
});
const inviteMember = () => {
  addExistingFormRef.value?.validate(async (valid) => {
    if (valid) {
      isLoading.value = true;
      let fileItem = new FormData();
      fileItem.append("evidenceType", addExistingForm.evidenceType);
      fileItem.append("evidenceName", addExistingForm.evidenceName);
      fileItem.append("useEncrypt", addExistingForm.useEncrypt);
      addExistingForm.file.forEach((item) => {
        fileItem.append("file", item.raw);
      });
      let hashParmars = {
        evidenceName: addExistingForm.evidenceName,
        fileInfo: addExistingForm.fileInfo,
      };
      const { success, msg } =
        addExistingForm.evidenceType === "0"
          ? await createEvidenceFileHash(hashParmars)
          : await createEvidenceFile(fileItem);
      if (success) {
        isLoading.value = false;
        ElMessage.success(msg || "创建成功");
        router.push({ path: "/ExistingEvidence/DocumentStorageCertificate" });
      } else {
        isLoading.value = false;
        ElMessage.error(msg || "创建失败,请稍后再试");
      }
    } else {
      return false;
    }
  });
};
const handleExceed = () => {
  ElMessage.error("最多上传10个文件！");
};
const changeAvatarUploadFront = (rawFile, fileList) => {
  const typeAarry = [".jpg", ".png", ".JPG", ".PNG", ".zip"];
  const typeVideoAudioAarry = [".mp4", ".zip", ".mp3"];
  const typeDocAarry = [
    ".doc",
    ".docx",
    ".xlsx",
    ".pdf",
    ".ppt",
    ".html",
    ".zip",
    ".txt",
  ];
  const typeAllRoundAarry = [
    ".jpg",
    ".png",
    ".JPG",
    ".PNG",
    ".mp4",
    ".mp3",
    ".zip",
    ".doc",
    ".docx",
    ".xlsx",
    ".pdf",
    ".ppt",
    ".html",
    ".txt",
  ];
  const type = rawFile.name.substring(rawFile.name.lastIndexOf("."));
  switch (addExistingForm.evidenceType) {
    case "1":
      isZip.value = true;
      if (type === ".zip") {
        isZip.value = false;
      }
      const isImage = typeAarry.indexOf(type) > -1;
      if (!isImage) {
        ElMessage.error("上传文件必须为.png，.jpg，.zip格式图片");
        if (addExistingForm.file.length <= 0) {
          addExistingForm.file = [];
        } else {
          addExistingForm.file = addExistingForm.file.filter((item) => {
            return item.name !== rawFile.name;
          });
        }
      } else if (rawFile.size / 1024 / 1024 > 100) {
        ElMessage.error("上传文件必须在100MB以内");
        if (addExistingForm.file.length <= 0) {
          addExistingForm.file = [];
        } else {
          addExistingForm.file = addExistingForm.file.filter((item) => {
            return item.name !== rawFile.name;
          });
        }
      }
      break;
    case "2":
      const isDoc = typeDocAarry.indexOf(type) > -1;
      if (!isDoc) {
        ElMessage.error(
          "上传文件必须为.doc，.docx，.pdf，.ppt，.html，.txt，.xlsx，.zip格式文档"
        );
        if (addExistingForm.file.length <= 0) {
          addExistingForm.file = [];
        } else {
          addExistingForm.file = addExistingForm.file.filter((item) => {
            return item.name !== rawFile.name;
          });
        }
      } else if (rawFile.size / 1024 / 1024 > 20) {
        ElMessage.error("上传文件必须在20MB以内");
        if (addExistingForm.file.length <= 0) {
          addExistingForm.file = [];
        } else {
          addExistingForm.file = addExistingForm.file.filter((item) => {
            return item.name !== rawFile.name;
          });
        }
      }
      break;
    case "3":
      const isVideoAudio = typeVideoAudioAarry.indexOf(type) > -1;
      if (!isVideoAudio) {
        ElMessage.error("上传文件必须为mp3，mp4，.zip格式音频视频");
        if (addExistingForm.file.length <= 0) {
          addExistingForm.file = [];
        } else {
          addExistingForm.file = addExistingForm.file.filter((item) => {
            return item.name !== rawFile.name;
          });
        }
      } else if (rawFile.size / 1024 / 1024 > 500) {
        ElMessage.error("上传文件必须在500MB以内");
        if (addExistingForm.file.length <= 0) {
          addExistingForm.file = [];
        } else {
          addExistingForm.file = addExistingForm.file.filter((item) => {
            return item.name !== rawFile.name;
          });
        }
      }
      break;
    case "4":
      const isAllRound = typeAllRoundAarry.indexOf(type) > -1;
      if (!isAllRound) {
        ElMessage.error(
          "上传文件必须为.png，.jpg，.doc，.docx，.pdf，.ppt，.html，.txt，.xlsx，mp3，mp4，.zip格式综合类型"
        );
        if (addExistingForm.file.length <= 0) {
          addExistingForm.file = [];
        } else {
          addExistingForm.file = addExistingForm.file.filter((item) => {
            return item.name !== rawFile.name;
          });
        }
      } else if (rawFile.size / 1024 / 1024 > 200) {
        ElMessage.error("上传文件必须在200MB以内");
        if (addExistingForm.file.length <= 0) {
          addExistingForm.file = [];
        } else {
          addExistingForm.file = addExistingForm.file.filter((item) => {
            return item.name !== rawFile.name;
          });
        }
      }
      break;
  }
  return true;
};
const addDomain = () => {
  if (addExistingForm.fileInfo.length > 9) {
    ElMessage.error("文件最多添加10条！");
    return false;
  }
  addExistingForm.fileInfo.push({
    name: "",
    url: "",
    hash: "",
  });
};
const removeDomain = (index) => {
  if (index !== 0) {
    addExistingForm.fileInfo.splice(index, 1);
  }
};
</script>

<style lang="scss" scoped>
@import "../../assets/css/cindex.scss";
@import "../../assets/css/position";
:deep .el-upload-list--picture-card .el-upload-list__item-actions span + span {
  margin-left: 0.5em;
}
@media screen and (max-width: 1366px) {
  .txt_content {
    background: #f6f6ff;
    padding: 10px;
    margin-left: 10px;
    height: 1.2rem;
  }
}
@media screen and (min-width: 1367px) {
  .txt_content {
    background: #f6f6ff;
    padding: 10px;
    margin-left: 10px;
    height: 0.9rem;
  }
}
@media screen and (min-width: 1920px) {
  .txt_content {
    background: #f6f6ff;
    padding: 10px;
    margin-left: 10px;
    height: 0.6rem;
  }
}
// .el-row {
//     margin-bottom: 15px;
// }
.add_icon {
  font-size: 18px;
  margin-left: 10px;
  cursor: pointer;
  height: 100%;
}
.delete_icon {
  font-size: 18px;
  margin-left: 10px;
  cursor: pointer;
  height: 100%;
}
</style>
